package com.dal.userbackend.controller;


import com.dal.userbackend.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/api/")
@Slf4j
public class UserController {

    final static String USER_PREFIX = "registerUser_";

    @Autowired
    RedisTemplate redisTemplate;

//    用户注册接口
    @PostMapping("/register/")
    public String registerUser(@RequestBody User userInfo) {
        log.info("{}",userInfo);
        var userKey=USER_PREFIX+userInfo.getName();
        User user_old = (User) redisTemplate.opsForValue().get(userKey);
        if (user_old!=null){
            throw new RuntimeException("用户已经存在。");
        }
        redisTemplate.opsForValue().set(USER_PREFIX+userInfo.getName(), userInfo);

        return "ok";
    }
    public Set<String> getListKey(String prefix) {
        return redisTemplate.keys(prefix.concat("*"));
    }
    @GetMapping("/users/")
    List<User> getUsers(){
        var keys=getListKey(USER_PREFIX);
        log.info("keys : {}",keys);
        List<User> users= redisTemplate.opsForValue().multiGet(keys);
        log.info("users : {}",users);
        return users;
    }
}
